﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;

namespace MagicSoundPro
{
    public class LowPassFilter
    {
        private float[] _kernel;

        public LowPassFilter(int sampleRate, float cutoffFrequency)
        {
            int kernelSize = 2 * sampleRate / 1000;
            _kernel = new float[kernelSize];

            float omegaC = 2 * (float)Math.PI * cutoffFrequency / sampleRate;

            for (int i = 0; i < kernelSize; i++)
            {
                if (i == kernelSize / 2)
                {
                    _kernel[i] = omegaC / (float)Math.PI;
                }
                else
                {
                    _kernel[i] = (float)(Math.Sin(omegaC * (i - kernelSize / 2)) / (Math.PI * (i - kernelSize / 2)));
                }

                _kernel[i] *= (float)(0.54 - 0.46 * Math.Cos(2 * Math.PI * i / kernelSize));
            }
        }

        public void Apply(Complex[] data)
        {
            int kernelSize = _kernel.Length;
            int dataSize = data.Length;

            for (int i = 0; i < dataSize; i++)
            {
                float sumReal = 0;
                float sumImag = 0;

                for (int j = 0; j < kernelSize; j++)
                {
                    int index = i - kernelSize / 2 + j;

                    if (index >= 0 && index < dataSize)
                    {
                        sumReal += (float)(data[index].Real * _kernel[j]);
                        sumImag += (float)(data[index].Imaginary * _kernel[j]);
                    }
                }

                data[i] = new Complex(sumReal, sumImag);
            }
        }
    }
}
